package service

import (
	"fly/models"
	"github.com/beego/beego/v2/client/orm"
	"github.com/duke-git/lancet/v2/slice"
)

type SysRoleMenuService struct {
	BaseService
}

func (c *SysRoleMenuService) SaveOrUpdate(roleId int64, menuIdList []int64, operator int64) (err error) {
	//先删除角色菜单关系
	_, err = orm.NewOrm().QueryTable(new(models.SysRoleMenu)).Filter("role_id", roleId).Delete()
	if len(menuIdList) == 0 {
		return nil
	}
	o := orm.NewOrm()
	for _, menuId := range menuIdList {
		_, err = o.Insert(&models.SysRoleMenu{
			BaseModel: models.BaseModel{Creator: operator},
			RoleId:    roleId,
			MenuId:    menuId,
		})
	}
	return
}

func (c *SysRoleMenuService) GetMenuIdList(roleId int64) (ids []int64, err error) {
	var list []*models.SysRoleMenu
	_, err = orm.NewOrm().QueryTable(new(models.SysRoleMenu)).Filter("role_id", roleId).All(&list, "menu_id")
	if err != nil {
		return []int64{}, err
	}
	ids = slice.Map(list, func(index int, item *models.SysRoleMenu) int64 {
		return item.MenuId
	})
	return ids, nil
}
